package site.xuxingcan;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

public class Main {
    public static int HTTP_PORT = 8090, MESSAGE_PORT = 8191;

    public static void main(String[] args) throws Exception {
        // write your code here
        if (args.length != 2) {
            System.out.println("please input 2 parameters HTTP_PORT and MESSAGE_PORT");
            return;
        } else {
            try {
                HTTP_PORT = Integer.parseInt(args[0]);
                MESSAGE_PORT = Integer.parseInt(args[1]);
                if (HTTP_PORT == MESSAGE_PORT) {
                    System.out.println("HTTP_PORT and MESSAGE_PORT cannot be the same");
                    return;
                }
            } catch (Exception e) {
                System.out.println("please input 2 parameters HTTP_PORT and MESSAGE_PORT");
                return;
            }
        }
        System.out.println("HTTP_PORT is " + HTTP_PORT + "\nMESSAGE_PORT is " + MESSAGE_PORT);
        new Main().start();
    }

    public void start() throws Exception {
        ServerUtil.getInstance();
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(HTTP_PORT)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // server端发送的是httpResponse，所以要使用HttpResponseEncoder进行编码
                            socketChannel.pipeline().addLast(new HttpResponseEncoder());
                            // server端接收到的是httpRequest，所以要使用HttpRequestDecoder进行解码
                            socketChannel.pipeline().addLast(new HttpRequestDecoder());
                            socketChannel.pipeline().addLast(new HttpPostServerInboundHandler());
                        }
                    });
            ChannelFuture f = bootstrap.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

}
